import { createContext, memo, useCallback, useContext, useReducer, useRef, useState } from 'react'
import { Button } from 'antd'
import ToolBarView from '@/components/ToolBarView'

const initial = { num: 10 }
const Reducer = (state: any, action: any) => {
	switch (action.type) {
		case 'SET_NUM':
			return { ...state, num: action.data }
		default:
			return state
	}
}

const Context = createContext<any>(initial)

const List = memo(() => {
	// console.log('Home渲染了')
	// useBeforeEach()
	const [state, dispatch] = useReducer(Reducer, initial)
	const [bar, setBar] = useState<number>(0)
	const num = useRef<number>(0)
	num.current = bar

	// console.log('RouteList')

	const handle = useCallback(() => {
		setBar(num.current + 1)
	}, [])

	const action = {
		increment() {
			dispatch({ type: 'SET_NUM', data: state.num + 1 })
		}
	}

	return (
		<Context.Provider value={{ ...state, ...action }}>
			<div style={{ height: '1000px' }}>
				<ToolBarView
					align="left"
					toolbar={[
						<Custom key="foo" />,
						{ label: '我是按钮1', type: 'primary', onClick: () => console.log('我是按钮1') },
						{ label: '按钮', type: 'primary', onClick: () => console.log('按钮') },
						{ label: '穿山甲', type: 'primary', onClick: () => console.log('穿山甲') },
						{ label: '杰哥', type: 'primary', onClick: () => console.log('杰哥') },
						{ label: '打印', type: 'primary', onClick: () => console.log('打印') },
						{ label: '劈我瓜是吧', type: 'primary', onClick: () => console.log('劈我瓜是吧') }
					]}
				/>
				<h2>{bar}</h2>
				<Foo handle={handle} />
				<Bar />
			</div>
		</Context.Provider>
	)
})

const Custom = memo(() => {
	return (
		<Button type="primary" danger onClick={() => console.log('我是按钮')}>
			我是按钮
		</Button>
	)
})

const Foo = memo((props: { handle?: () => void }) => {
	// console.log('Foo渲染了')
	const { increment, num } = useContext(Context)

	return (
		<div>
			<button onClick={props.handle}>handle+1</button>
			<h2>{num}</h2>
			<button onClick={increment}>++++</button>
		</div>
	)
})

const Bar = memo(() => {
	// console.log('Bar')
	return <h2>Bar</h2>
})

export default List
